package com.cmos.service.impl;

import com.cmos.dao.RoleDao;
import com.cmos.dao.RolePrivilegeDao;
import com.cmos.entity.Role;
import com.cmos.entity.RolePrivilege;
import com.cmos.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
    //注入角色DAO
    @Resource
    private RoleDao roleDao;
    //注入角色-权限DAO
    @Resource
    private RolePrivilegeDao rolePrivilegeDao;

    //添加角色
    @Override
    public int saveRole(Role role, String[] ids) {
        //根据ids 将角色的新权限添加到role_privilege表
        List<RolePrivilege> rolePrivileges = new ArrayList<>();
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                RolePrivilege rolePrivilege = new RolePrivilege();
                rolePrivilege.setId(UUID.randomUUID().toString().replace("-", ""))
                        .setRoleId(role.getId()).setPrivilegeId(id);
                rolePrivileges.add(rolePrivilege);
            }
        }
        rolePrivilegeDao.insertRolePrivilege(rolePrivileges);
        return roleDao.insert(role);
    }

    //删除角色
    @Override
    public int removeRole(String id) {
        return roleDao.deleteByPrimaryKey(id);
    }

    //修改角色信息
    @Override
    public int changeRole(Role role, String[] ids) {
        //删除角色的所有权限
        rolePrivilegeDao.delete(new RolePrivilege().setRoleId(role.getId()));
        //为角色添加新权限
        List<RolePrivilege> rolePrivileges = new ArrayList<>();
        if (ids != null && ids.length > 0) {
            for (String id : ids) {
                RolePrivilege rolePrivilege = new RolePrivilege();
                rolePrivilege.setId(UUID.randomUUID().toString().replace("-", ""))
                        .setRoleId(role.getId()).setPrivilegeId(id);
                rolePrivileges.add(rolePrivilege);
            }
        }
        rolePrivilegeDao.insertRolePrivilege(rolePrivileges);
        return roleDao.updateByPrimaryKeySelective(role);
    }

    //查询角色信息
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Role queryRole(Role role) {
        return roleDao.selectRole(role);
    }

    //查询所有角色
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public List<Role> queryAllRole() {
        return roleDao.selectAllRole();
    }

    //给角色添加权限
    @Override
    public Integer saveRolePrivilege(List<RolePrivilege> rolePrivileges) {
        return rolePrivilegeDao.insertRolePrivilege(rolePrivileges);
    }

    //删除角色权限
    @Override
    public Integer removeRolePrivilege(String roleId) {
        return rolePrivilegeDao.delete(new RolePrivilege().setRoleId(roleId));
    }
}
